<template>
  <app-config-provider>
    <view class="outer-app-demo-plugin">
      <view class="inner-app-demo-plugin">
        <!-- <uni-card title="地图"> -->
        <div ref="mapRef" class="map" style="width: 100%; height: 450px"></div>
        <!-- </uni-card> -->
        <button class="button-view" type="primary" @click="onMarkerClick"> 查看列表页面 </button>
        <button class="button-view" type="primary" @click="goFunForm()"> 请假表单页面 </button>
      </view>
    </view>
  </app-config-provider>
</template>

<script>
  import { onMounted, reactive, defineComponent, onBeforeMount, toRefs, watch, h } from 'vue';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { getFuncDataList } from './api/demo.js';
  import { onShow } from '@dcloudio/uni-app';
  import { Modal } from '@jecloud/utils';
  import { Func, showSelectWindow } from '@jecloud/app-func';

  export default defineComponent({
    name: 'Maps',
    components: {},
    setup() {
      const option = reactive({
        lng: 116.404,
        lat: 39.915,
        AMap: null,
        mapRef: null,
        mapData: null,
        data: [],
        markers: [],
      });
      const methods = {
        // 配置map
        initConfigMap() {
          AMapLoader.load({
            key: '651bbe1427b37c74deea8541a643918a', // 申请好的Web端开发者Key，首次调用 load 时必填
            plugins: [
              'AMap.Scale',
              'AMap.ToolBar',
              'AMap.PlaceSearch',
              'AMap.Geolocation',
              'AMap.Geocoder',
              'AMap.Autocomplete',
              'AMap.OverView',
              'AMap.MapType',
              'AMap.PolyEditor',
              'AMap.CircleEditor',
              'AMap.DistrictSearch',
              'AMap.CircleMarker',
              'AMap.Polyline',
              'AMap.Pixel',
            ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            AMapUI: {
              version: '1.1',
              plugins: ['overlay/SimpleMarker', 'geo/DistrictExplorer'],
            },
          }).then((map) => {
            option.AMap = map;
            option.mapData = methods.initMap(map);

            return option.mapData;
          });
        },
        // 初始化地图
        initMap(AMap) {
          const mapData = new AMap.Map(option.mapRef, {
            mapStyle: 'amap://styles/98b26d04358dd80ee479ca1dfe9edd06', // 配置的地图样式
            zoom: 5,
            zooms: [1, 20],
            center: [116.404, 39.915],
            features: ['road', 'bg', 'point', 'building'], // 支持'bg'（地图背景）、'point'（POI点）、'road'（道路）、'building'（建筑物）
            resizeEnable: true, // 监控地图容器尺寸变化，默认值为false
            expandZoomRange: true, // 支持可以扩展最大缩放级别，和zooms属性配合使用，设置为true的时候，zooms的最大级别在PC上可以扩大到20级
          });
          mapData.on('click', (e) => {
            console.log(e);
          });
          return mapData;
        },
        getRandom(min, max) {
          return Math.floor(Math.random() * (max - min + 1) + min);
        },
        // Marker
        inintMarker(item, index) {
          const marker = new option.AMap.Marker({
            map: option.mapData,
            icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            position: [option.lng + 0.01 * index, option.lat + 0.01 * index],
            offset: new option.AMap.Pixel(
              methods.getRandom(-200, 200),
              methods.getRandom(-100, 100),
            ),
            id: item.HR_QJSQ_ID,
            content: `<div style="background: yellow;border-radius: 50%;width: 40px;height: 40px;text-align: center;line-height: 40px">${
              index + 1
            }</div>`,
          });
          marker.content = item.HR_QJSQ_ID;
          // 点击事件
          marker.on('click', (e) => {
            methods.goFunForm(e.target.content);
          });

          return marker;
        },
        // 进入表单
        goFunForm(id) {
          uni.navigateTo({
            url: id ? `/pages/demo/form?id=${id}` : '/pages/demo/form',
          });
        },
        // 获取列表数据
        getFuncData() {
          const params = {
            tableCode: 'HR_QJSQ',
            funcCode: 'HR_QJSQ',
          };
          getFuncDataList(params).then((data) => {
            option.data = data.rows;
          });
        },
        // 点击查看列表
        onMarkerClick() {
          showSelectWindow({
            configInfo: 'HR_QJSQ,grid,HR_QJSQ_ID',
            type: 'grid',
            value: '',
            callback: ({ rows }) => {
              if (rows && rows[0].HR_QJSQ_ID) {
                methods.goFunForm(rows[0].HR_QJSQ_ID);
              }
            },
          });
        },
      };

      watch(
        () => [option.AMap, option.data],
        (val, value1) => {
          if (!(option.AMap && value1.length)) {
            return false;
          }
          // 清除标记点
          option.mapData.remove(option.markers);
          option.markers = [];
          // 渲染标记点
          option.data.map((item, index) => {
            const marker = methods.inintMarker(item, index);
            option.markers.push(marker);
          });
        },
        { deep: true },
      );
      onBeforeMount(() => {});
      onMounted(() => {
        // 初始地图
        methods.initConfigMap();
        // 获取列表数据
        methods.getFuncData();
      });
      onShow(() => {
        uni.$on('updateData', () => {
          methods.getFuncData();
        });
      });
      return { ...toRefs(option), ...methods };
    },
  });
</script>
<style lang="scss" scoped>
  .outer-app-demo-plugin {
    width: 100%;
    height: calc(100vh - var(--window-top)) !important;
    .inner-app-demo-plugin {
      width: 100%;
      height: 100%;
      overflow: auto;
    }

    .button-view {
      width: 60%;
      margin-top: 30px;
    }
    .func-height {
      height: 600px;
    }
  }
</style>
